#if UNITY_EDITOR

using System.IO;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using ZhiSe;

[InitializeOnLoad]
public class SeegEnvInit
{
    static SeegEnvInit()
    {
        Seeg.InitParam(GetCfg());
    }

    private static JObject GetCfg()
    {
        var configPath = $"{Application.dataPath}/Seeg/Editor/Cfg/sdk_config.json";
        if (!File.Exists(configPath))
        {
            return null;
        }
        var json = File.ReadAllText(configPath);
        if (string.IsNullOrEmpty(json))
        {
            return null;
        }
        var sdkParam = JObject.Parse(json);
        var gid = sdkParam.Value<string>("current");
        if (string.IsNullOrEmpty(gid))
        {
            return null;
        }

        var info = sdkParam.Value<JObject>("info");
        if (null == info || !info.ContainsKey(gid))
        {
            Debug.LogWarning("[SEEG] SeegSDK的构建配置没有包含当前gid的构建信息");
            return null;
        }
        
        var infoData = info.Value<JObject>(gid);
        if (null == infoData)
        {
            Debug.LogWarning("[SEEG] SeegSDK的构建配置没有包含当前gid的构建信息");
            return null;
        }

        var sdkData = GetSdkCfg(gid);
        if (null == sdkData)
        {
            return infoData;
        }
        foreach (var item in sdkData)
        {
            infoData[item.Key] = item.Value;    
        }

        return infoData;
    }

    private static JObject GetSdkCfg(string gid)
    {
        if (gid.EndsWith("_"))
        {
            return null;
        }

        if (!gid.StartsWith("hgg_") && !gid.StartsWith("hios_"))
        {
            return null;
        }

        var sdkCfgPath = $"{Application.dataPath}/Seeg/Editor/Cfg/{gid}/seeg_sdk_param.json";
        if (!File.Exists(sdkCfgPath))
        {
            return null;
        }
        
        var sdkCfgStr = File.ReadAllText(sdkCfgPath);
        if (string.IsNullOrEmpty(sdkCfgStr))
        {
            return null;
        }
        
        var sdkCfg = JObject.Parse(sdkCfgStr);
        return sdkCfg.Value<JObject>("info");
    }

}
#endif